/**
 * 分屏对比
 * @copyright 火星科技 mars3d.cn
 * @author 火星胡椒 2022-01-10
 */
import * as mars3d from "mars3d"
import "./mapCompare.less"
let map: mars3d.Map

let centerDiv: HTMLElement

const mapExArr = [
  {
    id: "centerDivEx1",
    containerId: "mars3dContainerEx1",
    mapEx: null,
    basemap: "黑色底图",
    top: "0%",
    left: "50%"
  },
  {
    id: "centerDivEx2",
    containerId: "mars3dContainerEx2",
    mapEx: null,
    basemap: "蓝色底图",
    top: "50%",
    left: "0%"
  },
  {
    id: "centerDivEx3",
    containerId: "mars3dContainerEx3",
    mapEx: null,
    basemap: "高德电子",
    top: "50%",
    left: "50%"
  }
]

// 初始化当前业
export function onMounted(mapInstance: mars3d.Map): void {
  map = mapInstance // 记录map

  centerDiv = document.getElementById("centerDiv")
  centerDiv.style.height = "50%"
  const center: HTMLElement = map.container
  center.style.width = "50%"
  center.style.height = "100%"

  const mapOptions2 = map.toJSON()
  // 绑定的控件
  mapOptions2.control.baseLayerPicker = true // basemaps底图切换按钮
  mapOptions2.control.sceneModePicker = false

  // 用于双屏同图层，不同配置展示
  mapOptions2.layers.forEach((item) => {
    if (item.compare) {
      // 存在compare属性时
      for (const key in item.compare) {
        item[key] = item.compare[key]
      }
    }
  })

  // 后置加的图层的处理
  const mapLayers = map.getLayers({
    basemaps: false, // 排除config.json中的basempas
    layers: false // 排除config.json中的layers
  })

  for (let i = mapLayers.length - 1; i >= 0; i--) {
    const layer = mapLayers[i]
    if (layer.isPrivate || layer.parent) {
      continue
    }
    mapOptions2.layers.push(layer.toJSON())
  }

  console.log("分屏地图配置", mapOptions2)

  const marsDiv = document.getElementById("mars-main-view")

  // 参数配置
  mapExArr.forEach((item) => {
    const centerDivEx = mars3d.DomUtil.create("div", "", marsDiv)
    centerDivEx.setAttribute("id", item.id)
    centerDivEx.style.display = "block"
    centerDivEx.style.height = "50%"
    centerDivEx.style.width = "50%"
    centerDivEx.style.position = "absolute"
    centerDivEx.style.top = item.top
    centerDivEx.style.left = item.left
    const mars3dContainerEx = mars3d.DomUtil.create("div", "mars3d-container", centerDivEx)
    mars3dContainerEx.setAttribute("id", item.containerId)

    item.mapEx = new mars3d.Map(mars3dContainerEx, mapOptions2)
    item.mapEx.basemap = item.basemap
  })
}

// 释放当前业务
export function onUnmounted(): void {
  // 组件销毁时的操作
  const centerDivDom: HTMLElement = map.container
  centerDivDom.style.height = "100%"
  centerDivDom.style.width = "100%"
  centerDivDom.style.right = "0"
  centerDiv.style.right = "0"
  centerDiv.style.height = "100%"

  mapExArr.forEach((item) => {
    const creatDom: HTMLElement = document.getElementById(item.id)
    creatDom.remove()
    item.mapEx = null
  })
}
